//
//  WBRefreshControl.swift
//  Weibo
//
//  Created by 潇 on 16/1/1.
//  Copyright © 2016年 潇. All rights reserved.
//

import UIKit
import SnapKit


enum WBRefreshStatue: Int {
    case Normal = 0     //默认状态
    case Pulling = 1    //用户下拉临界状态
    case Refreshing = 2 //正在刷新状态
}

//刷新控件的高度
private let RefreshViewHight: CGFloat = 60

class WBRefreshControl: UIControl {
    
    //定义属性,保存上一次刷新的状态
    var oldStatue: WBRefreshStatue = .Normal
    
    //MARK: 定义外部模型属性
    var statue: WBRefreshStatue = .Normal {
        didSet {
            //根据不同的状态  更改显示的逻辑
            switch statue {
            case .Pulling:
                print("准备起飞")
                //1.修改提示文案
                tipLabel.text = "准备起飞"
                //2.旋转箭头
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform =
                    CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
            case .Refreshing:
                print("正在起飞")
                tipLabel.text = "正在起飞"
                //隐藏箭头  显示转动的小菊花
                arrowIcon.hidden = true
                loadIcon.startAnimating()
                //应该主动触发 Control 的方法响应事件
                //修改 contentInset
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    var inset = self.scrollView!.contentInset
                    inset.top += RefreshViewHight
                    self.scrollView?.contentInset = inset
                })
                
                
                sendActionsForControlEvents(.ValueChanged)
                
            case .Normal:
                //回到从前最初的状态
                arrowIcon.hidden = false
                loadIcon.stopAnimating()
                print("下拉起飞")
                tipLabel.text = "下拉起飞"
                loadIcon.stopAnimating()
                
                //修改 contentInset  inset,Top 会被多减一次
                if oldStatue == .Refreshing {
                
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        var inset = self.scrollView!.contentInset
                        inset.top -= RefreshViewHight
                        self.scrollView?.contentInset = inset
                    })
                }

                
                //重置箭头方向
                UIView.animateWithDuration(0/25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformIdentity

                })
            }
            //所有设置结束后,保存上一次的刷新状态
            oldStatue = statue
        }
    }
    
    //实现 kvo 方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        print(change)
        //1.获取 tableView 的临界值
        let insetTop = scrollView?.contentInset.top ?? 0
        let condationValue = -(RefreshViewHight + insetTop)
        //2.获取 tableView 的 contentOffset
        let offSetY = scrollView?.contentOffset.y ?? 0
        
        if scrollView!.dragging {
        
            if statue == .Normal && offSetY < condationValue {
                //进入用户下拉到临界值   还没松手刷新的状态
                statue = .Pulling
            }else if statue == .Pulling && offSetY > condationValue {
                //进图默认状态
                statue = .Normal
            }
        }else {
            //不是在被拉拽的状态  并且当前的视图的 statue 是 pulling 状态,在执行属性操作
            if statue == .Pulling {
                statue = .Refreshing
            }
        }
        
        
        //3.比较对应的临界值和位移大小
    }
    
    func endRefreshing() {
        
        //延迟加载  让加载效果显示久一点
        let delta = dispatch_time(DISPATCH_TIME_NOW, Int64(1) * Int64( NSEC_PER_SEC))
        dispatch_after(delta, dispatch_get_main_queue()) { () -> Void in
            self.statue = .Normal
        }
    }
    
    //view的生命周期方法
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        //可以获取到当前控件的父视图
        //1.获取 tableView
        if let myFather = newSuperview as? UIScrollView {
            //如果父视图能够转化为滚动视图
            //观察滚动视图的 contentOffset
            self.scrollView = myFather
            //设置 kvo
            self.scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        }
        
    }
    
    //移除 kvo观察
    deinit {
        self.scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    
    
    //重写构造方法
    override init(frame: CGRect) {
        
        //在视图内部执行 frame
        let rect = CGRect(x: 0, y: -RefreshViewHight, width: screenW, height: RefreshViewHight)
        
        super.init(frame: rect)
        
        
        //设置视图
        setupUI()
        //设置颜色
        backgroundColor = UIColor.rendomColor()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK:设置页面和布局
    private func setupUI() {
        addSubview(arrowIcon)
        addSubview(tipLabel)
        addSubview(loadIcon)
        
        //设置约束
        tipLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(10)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(tipLabel.snp_left).offset(-30)
            make.centerY.equalTo(tipLabel.snp_centerY)
        }
        
        loadIcon.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon)
        }
    }
    
    //定义属性  记录父视图
    var scrollView: UIScrollView?
    
    //MARK: 懒加载所有的子视图
    private lazy var arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    private lazy var tipLabel: UILabel = UILabel(title: "下拉起飞", color:  UIColor.rendomColor(), fontSize: 14)
    
    private lazy var loadIcon: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)


}
